import React, {
  useContext,
  useState
} from "react";

export const GridContext = React.createContext({});
GridContext.displayName = "GridContext";

// GridContext的数据提供者
export const GridProvider = ({
  children
}) => {
  const [gridList, setGridList] = useState([{}, {}, {}, {}, {}, {}, {}, {}, {}]);

  // 拖拽后更新gridList的状态
  const updateGridHandler = (info, location) => {
    const newGridList = gridList.map((item, index) => {
      if (index === location) item = info
      return item;
    })
    setGridList(newGridList);
  }
  // 设置所在奖池宫格的概率
  const updateGridValue = (value, location, type) => {
    const newGridList = gridList.map((item, index) => {
      if (index === location) {
        switch (type) {
          case 'title':
            item.title = value;
            break;
          case 'prob':
            value = value > 100 ? 100 : (value < 0 ? 0 : parseInt(value));
            item.prob = value;
            break
          case 'releaseProb':
            value = value > 100 ? 100 : (value < 0 ? 0 : parseInt(value));
            item.releaseProb = value;
            break
          default:
            break;
        }
      }
      return item;
    })
    setGridList(newGridList);
  }

  return <GridContext.Provider value = {
    {
      gridList,
      updateGridHandler,
      updateGridValue
    }
  }
  children = {
    children
  }
  />
}

// GridContext的数据接收者
export const GridConsumer = ({
  children
}) => {
  return <GridContext.Consumer children = {
    children
  }
  />
}

// 封装grid的useContext的hook
export const useGridContext = () => {
  const context = useContext(GridContext);
  return context;
}